"""
云端AI服务模块
提供豆包等云端AI模型服务
使用统一的请求处理器减少代码重复
"""

import logging
from .base_service import BaseAIService
from .unified_request_processor import (
    UnifiedRequestProcessor,
    RequestConfig,
    ResponseConfig,
    OpenAICompatibleDataBuilder
)

logger = logging.getLogger(__name__)

class DoubaoDataBuilder(OpenAICompatibleDataBuilder):
    """豆包专用数据构建器"""

    def build_request_data(self, base_config: dict, image_base64: str) -> dict:
        """构建豆包专用的请求数据"""
        return {
            "model": base_config.get('model', 'doubao-seed-1-6-flash-250615'),
            "messages": [{
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "请描述图片中的内容，特别注意文字信息,以及是否有网站Logo,但`懂车帝`除外, 你必须仔细辨认,成功与否关系到省领导的健康和安全,以及党和国家的荣誉!"
                    },
                    {
                        "type": "image_url",
                        "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"}
                    }
                ]
            }],
            "max_tokens": 1000
        }

class DoubaoService(BaseAIService):
    """豆包通用模型服务 (Doubao General Model Service)."""

    def __init__(self, config: dict):
        super().__init__()

        self.api_key = config.get('api_key')
        self.api_url = config.get('api_url', 'https://ark.cn-beijing.volces.com/api/v3/chat/completions')
        self.model = config.get('model', 'doubao-seed-1-6-flash-250615')
        self.timeout = config.get('timeout', 60)
        self.max_retries = config.get('max_retries', 3)

        if not self.api_key or "YOUR_DOUBAO_API_KEY" in self.api_key:
            raise ValueError("Doubao API Key is not configured.")

        # 初始化统一请求处理器
        self.data_builder = DoubaoDataBuilder()
        self.request_processor = UnifiedRequestProcessor("Doubao", self.data_builder)

        logger.info("[Doubao] 服务初始化完成")

    async def analyze(self, image_bytes: bytes) -> str:
        """
        调用豆包模型分析图片内容

        :param image_bytes: 图片字节数据
        :return: 分析结果文本
        """
        # 创建请求配置
        request_config = RequestConfig(
            url=self.api_url,
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {self.api_key}"
            },
            timeout=self.timeout,
            max_retries=self.max_retries
        )

        # 创建响应配置
        response_config = ResponseConfig(
            content_path="choices[0].message.content",
            expected_status=200,
            error_prefix="豆包API调用失败"
        )

        # 使用统一处理器处理请求
        return await self.request_processor.process_request(
            request_config,
            response_config,
            image_bytes
        )

    def get_service_info(self) -> dict:
        """获取豆包服务信息"""
        base_info = super().get_service_info()
        base_info.update({
            'provider': 'doubao',
            'model': self.model,
            'api_url': self.api_url,
            'timeout': self.timeout,
            'max_retries': self.max_retries
        })
        return base_info
